<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 班级管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <!-- <el-button
                type="danger"
                icon="el-icon-delete"
                class="handle-del mr10"
                @click="delAllSelection"
                :disabled="isDisabled"
                >删除</el-button> -->
				<el-button
                    type="primary"
                    icon="el-icon-circle-plus-outline"
                    class="handle-del mr10"
                    @click="handleAdd"
                >添加</el-button>
                <el-input v-model="query.className" placeholder="请输入" class="handle-input mr10"></el-input>
                <el-button 
                    type="primary"
                    icon="el-icon-search"
                    class="handled-del mr10"
                    @click="handleSearch"
                >搜索</el-button>
                <el-select v-model="query.facultyId" class="handle-select mr10" placeholder="学院" @change="facultyChange">
                    <el-option
                    v-for="item in facultyOptinos"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
                <el-button 
                    type="primary"
                    icon="el-icon-refresh"
                    class="handled-del mr10"
                    @click="handleReset"
                >重置</el-button>
            </div>
            <el-table
                v-loading="loading2"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0,0,0,0.8)"
                :data="tableList"
                border
                
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection"  align="center"></el-table-column>
                <el-table-column prop="classId" label="ID" align="center"></el-table-column>
                <el-table-column prop="className" label="班级" align="center"></el-table-column>
                <el-table-column prop="facultyName" label="学院" align="center"></el-table-column>
                <el-table-column label="操作"  align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="primary"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="danger"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

<!--  添加编辑弹出框  -->

            <el-dialog :close-on-click-modal="false"
                :title="titleMap[dialogStatus]"
                :visible.sync="dialogFormVisible" width="35%">

            <el-form :model="form" :rules="rules" ref="form" label-width="70px">
                <el-row :gutter="20">
                    <el-col :span="20">
                     <el-form-item label="学院" prop="facultyId">
                    <el-select v-model="form.facultyId" placeholder="请选择" >
                            <el-option
                                v-for="item in facultyOptinos"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                     </el-form-item>

                    </el-col>
                    <el-col :span="20">
                     <el-form-item label="班级" prop="className">
                         <el-input v-model="form.className" @blur="checkClass"></el-input>
                     </el-form-item>
                    </el-col>
                </el-row>
           </el-form>
            
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="dialogFormVisible = false">取 消</el-button>
            </span>
        </el-dialog>

    </div>
    
</template>

<script>
import{selectAllFaculty} from "@/api/faculty.js";
import{selectClassList,addClass,checkClassName,updateClass,deleteClass} from "@/api/class.js";
export default {
    name: 'class_manage',
    data() {
        return {
            date: '',
            //查询参数
            query: {
                className:'',
                facultyId:null,
                pageIndex: 1,
                pageSize: 10,
            },
            //新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
            titleMap: {
                add:'添加',
                edit: '编辑'
            },
            //新增和编辑弹框标题
            dialogStatus: "",
            // 遮罩层
            loading2: false,
            //表格数据
            tableData: [],
            flag:true,
            //表格
            tableList:[],

            // 批量删除按钮是否可以点击
            isDisabled: true,
            facultyOptinos:[],
            // 存放批量删除用户
            multipleSelection: [],
            //编辑框是否显示
            dialogFormVisible:false,
            //列表总数
            pageTotal: 0,
            form: {
                classId:null,
                facultyId:null,
                facultyName:'',
                className:'',
            },
            //校验规则
            rules:{
                className: [{ required: true, message: '请填写', trigger: 'blur' }],
                facultyId: [{ required: true, message: '请选择', trigger: 'blur' }],
            },
        };
    },
    watch: {
        // 监听最后一页删除最后一条数据时，当前页不变情况
        pageTotal(){
            if(this.pageTotal==(this.query.pageIndex-1)*this.query.pageSize && this.pageTotal!=0){
                this.query.pageIndex-=1;
                this.getData();
            }
        }
    },
    created() {
        //获取数据列表
		this.getData()
        this.getFaculty();
        
    },
    mounted(){

    },
    methods: {

         getFaculty(){
            const _this = this;
            selectAllFaculty().then((res)=>{
                let classes = res.data;
                _this.facultyOptinos =  classes.map((item) => {
                    //组装，只需要id和name
                    return { value: item.facultyId,label: item.facultyName };
                });
            })
        },
        submitForm(){
            const _this = this;
            if(this.flag){
                this.$refs["form"].validate(valid=>{
                    if(valid){
                        let formData = new FormData();
                        formData.append('facultyId',this.form.facultyId)
                        formData.append('className',this.form.className)


                //编辑操作
                if(this.form.classId!=undefined){
                    formData.append('classId',this.form.classId)
                    updateClass(formData).then(res=>{
                        this.$message.success(res.message)
                        this.dialogFormVisible = false
                        this.getData()
                    })
                }
                //添加操作
                else{
                    addClass(formData).then(res=>{
                        //console.log(res)
                        this.$message.success(res.message);
                        this.dialogFormVisible = false;
                        this.getData();
                    })
                }
            }
            })
            }
                

        },

        //添加操作
        handleAdd(){
            const _this = this
            this.resetForm();
            //显示弹框
            this.dialogFormVisible = true;
            //新增弹框标题
            this.dialogStatus = "add"
            this.unDisabled = false;
            this.pwdDisabled = false;

        },
        // 编辑操作
        handleEdit(index,row) {
            new Promise((resolve,reject)=>{
                this.resetForm();
                resolve();
            }).then(res=>{
                this.form = {...row};
                //this.form.facultyId = ''+row.facultyId;
                // console.log(row);
            })
            .catch(err=>{
                console.log(err)
            })
            this.flag = true;
            this.dialogFormVisible = true;
            this.dialogStatus = "edit"
        }, 

        checkClass(event){
        
            checkClassName(this.form.className,this.form.facultyId).then((res)=>{
                //console.log(res)
                if(res.code === 400){
                    this.$message.error(res.message);
                    this.flag = false;
                }else{
                    this.flag = true;
                }
            }).catch(err=>{
                console.log(err)
            })
        },
        

		//获取列表数据
		  getData(){
            //console.log("page:"+this.query.page)
            const _this = this
            this.loading2 = true
            selectClassList(this.query).then((res)=>{
			    console.log(res)
			    _this.tableList = res.data.records;
                _this.pageTotal = res.data.total;
            }).catch((err) => {
			        console.log('请求失败'+err)
			    });

            this.loading2 = false;
        },

        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index,row) {
            // 二次确认删除
            const _this = this
            const classId = row.classId
            this.$confirm('班级里的学生也会清空，确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                    deleteClass(classId).then(res=>{
                        this.$message.success('删除成功');
                        _this.getData()
                    })
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            }).catch(err=>{
                console.log('删除失败'+err)
            })
        },
        handleReset(){
            this.query.className = '';
            this.query.facultyId = null;
            this.getData();
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
            if(this.multipleSelection.length === 0){
                this.isDisabled = true;
            }else{
                this.isDisabled = false;
            }
        },
        //搜索
        handleSearch(){
            this.$set(this.query,'pageIndex',1);
            this.getData();
        },
              // 学院下拉改变
        facultyChange(){
            this.getData();
        },
        //批量删除
        delAllSelection() {
            const _this = this;
            this.$confirm('确定要删除吗?','提示',{
                type: 'warning'
            }).then(()=>{
                const length = _this.multipleSelection.length;
                let ids = '';
                for(let i = 0;i<length-1;i++){
                     ids+=_this.multipleSelection[i].facultyId+','
                }
                ids += _this.multipleSelection[length-1].facultyId;
                deleteTypes(ids).then(res=>{
                _this.$message.success(res.message);
                _this.multipleSelection = [];
                _this.getData();
            }).catch(err=>{
                console.log("出错了"+err)
            })
            })
        },
        // 分页导航
        handlePageChange(pageIndex){
            this.query.pageIndex = pageIndex
            this.getData();
        },
        //表单重置
        resetForm(){

            this.form = {
                classId:undefined,
                className: undefined,
                facultyName:undefined,
                facultyId:undefined
            }
            this.$nextTick(()=>{
                this.$refs.form.resetFields();
            })
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
